const options = require("./config/data.json")
const publicIP = require("public-ip")
const http = require("./http")
const cache = require("./cache")

const setCache = cache.set;

/**
 * 获取本机缓存
 */

function getCache(name){
    if(name) return cache.get("ip")
    return cache.getAll()
}

/**
 * 获取实时IP
 */
function nowIP(){
    return publicIP.v4()
}

/**
 * 更新缓存中的IP
 * @param {Function} onDiff IP不一致时调用
 */
async function updateCacheIP(onDiff){
    console.log("更新缓存中的IP......")
    let ip = await nowIP()
    const cacheIp = getCache("ip");
    if(!cacheIp || cacheIp!==ip){
        setCache('ip',ip,0)
        if(onDiff){
            Promise.resolve().then(()=>{
                onDiff(ip)
            })
        }
    }else{
        console.warn("ip没有变化")
    }
    return ip;
}

/**
 * 获取缓存中的IP
 */
function getCacheIP(){
    return getCache("ip")
}

function updateDnspod(ip){
    // const {sub_domain=[]} = getCache()
    const sub_domain = options.sub_domain
    
    return Promise.all(sub_domain.map(domain=>{
        return http.post("/Record.Ddns",{
            value:ip,
            sub_domain:domain,
        })
        .then(({data})=>data)
    }))
}


module.exports = {
    getCache,
    nowIP,
    updateCacheIP,
    getCacheIP,
    updateDnspod,
}